package com.biao.juc;

public class Demo04_ThreadLocal {
    /*
    ThreadLocal 主要提供每个线程缓存局部变量
     */
    public static void main(String[] args) {
        ThreadLocal<String> stringThreadLocal = new ThreadLocal<>();
        stringThreadLocal.set("aaa");
        stringThreadLocal.set("bbb");   // 替换掉了aaa
        System.out.println(stringThreadLocal.get());    // bbb

        new Thread(() -> {
            stringThreadLocal.set("ccc");   // 子线程中替换了bbb，但只作用在子线程内
            System.out.println("子线程：" + stringThreadLocal.get());   // 子线程：ccc
        }).start();
        // 主线程中再获取还是bbb
        System.out.println(stringThreadLocal.get());    // bbb

    }

    // ThreadLocal 实现原理
    /*
    public void set(T value) {
        Thread t = Thread.currentThread();  // 获取当前主线程
        ThreadLocalMap map = getMap(t);     // 每个线程都有ThreadLocalMap，获取主线程的ThreadLocalMap
        if (map != null)
            map.set(this, value);   // key是ThreadLocal，当前对象，value是set的值
        else
            createMap(t, value);
    }

    // get方法获取value时候，一样道理，就是拿ThreadLocal的当前对象去获取
    public T get() {
        Thread t = Thread.currentThread();
        ThreadLocalMap map = getMap(t);     // 得到线程的ThreadLocalMap
        if (map != null) {
            ThreadLocalMap.Entry e = map.getEntry(this);    // 通过this对象获取的value
            if (e != null) {
                @SuppressWarnings("unchecked")
                T result = (T)e.value;
                return result;      // 返回value
            }
        }
        return setInitialValue();
    }
     */

}
